package com.good.app.test

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebSettings
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.good.app.R
import com.good.app.base.BaseFragment
import com.good.app.databinding.ActivityNextBinding
import java.util.*

class NextFragment: BaseFragment() {

    lateinit var mBinding: ActivityNextBinding
    lateinit var mViewModel: NextViewModel
    private var result:String =""
    private var time:Int =0
    private var count:Int =0
    companion object{
        fun getInstance( result:String,time:Int,count:Int): NextFragment {
            var fragment=NextFragment()
            fragment.setResult(result,time,count)
            return fragment
        }
    }

    fun setResult(data:String,times:Int,counts:Int){
        result=data
        time=times
        count=counts
    }
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mBinding = ActivityNextBinding.inflate(inflater,container,false)
        mViewModel = ViewModelProvider(this).get(NextViewModel()::class.java)
        mBinding?.let {
            it.viewModel = mViewModel
            it.setLifecycleOwner(this)
        }
        mViewModel.tvResult.value = result
        setupListener()
        Timer().schedule(object : TimerTask() {
            override fun run() {
                mHandler.dispatchMessage(Message());

            }
        }, 0,1000)
        return mBinding.root
    }
    private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            activity!!.runOnUiThread(Runnable() {
                 run() {
                     timeAdd()

                 }
            });

        }
    }
    fun timeAdd(){
        time=time+1


        var textView:TextView= TextView(activity)
        textView.setText((time*count).toString())
        textView.setTextColor(activity!!.resources.getColor(R.color.textPrimary))
        mBinding.container.addView(textView)
    }
    fun setupListener(){
        mViewModel.submitEvent.observe(viewLifecycleOwner, Observer {
            Toast.makeText(context,mViewModel.submitEvent.value,Toast.LENGTH_LONG).show()
        })

    }


}